package com.BeatBox;

import java.util.Date;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.TextView;

public class BeatBox extends Activity implements OnClickListener {
	
	Handler handler = new Handler();
	private TextView mText;
	private ImageButton mButton01;
	private ImageButton mButton02;
	private HandlerThread mHandlerThread;
	private boolean isStop = true;
	
	TestCounter testcounter = new TestCounter();
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
    	
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        mText = (TextView) findViewById(R.id.textCount);
        
        mButton01 = (ImageButton) findViewById(R.id.imageButton1);
        mButton01.setOnClickListener(this);
        mButton02 = (ImageButton) findViewById(R.id.imageButton2);
        mButton02.setOnClickListener(this);
        
        mHandlerThread = new HandlerThread("clock");
        mHandlerThread.start();
    }
    
    
    
	public void onClick(View v) {
		
		if(v == mButton01)
			isStop = false;

		if(v == mButton02)
			isStop = true;
		
		atFrontOfQueue();
    }


	private void atFrontOfQueue(){
    	new Handler(Looper.getMainLooper()).postAtFrontOfQueue(new Runnable(){
    		public void run() {
    			if(!isStop){
        	        testcounter.TestCountUp();			
    			}
    	        // カウント表示
    	        mText.setText("Count:" + testcounter.GetTestCount());
    	        delayed();
    		}
    	});
	}
	
    private void delayed() {
    	new Handler(mHandlerThread.getLooper()).postDelayed(new Runnable(){
    		public void run() {
    			atFrontOfQueue();
    		}
    	}, 100);
    }
    
    @Override
    public void onDestroy() {
    	super.onDestroy();
    	mHandlerThread.getLooper().quit();
    	
    	/*
    	try {
    		mHandlerThread.join();
    	} catch (InterruptedException e) {
    		
    	}
    	*/
    }
    
}

